package com.ecreditpal.audio.wav.mfcc;

import java.io.*;
import java.nio.DoubleBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;

/**
 * @author lifeng
 * @version 1.0 on 2018/7/2.
 */
public class MFCCTest {
    private static final int SAMPLE_RATE = 16000;
    private static final int SAMPLE_DURATION_MS = 60000;
    private static final int RECORDING_LENGTH = (SAMPLE_RATE * SAMPLE_DURATION_MS / 1000);

    public static void main(String[] args) throws IOException {
        short tt = -707;
        byte[] cc = shortToBytes(tt);


        FileInputStream fis = new FileInputStream("/Users/lifeng/Downloads/py_speech_seg-master/dialog4.wav");
        DataInputStream dos = new DataInputStream(fis);

        FileInputStream fis2 = new FileInputStream("/Users/lifeng/Downloads/py_speech_seg-master/dialog4.wav");
        byte[] bb = new byte[RECORDING_LENGTH];
        int a = fis2.read(bb);

        ShortBuffer buffer = ShortBuffer.allocate(RECORDING_LENGTH);

        int n = 0;
        int size = 0;
        while (dos.available() >0) {
            short b = dos.readShort();
            n++;
            if (n < 23) {
                continue;
            }
            buffer.put(b);
            size++;
        }

        double[] doubleInputBuffer = new double[buffer.position()];
        short[] shortBuffer = buffer.array();
        for (int i = 0; i < buffer.position(); i++) {
            doubleInputBuffer[i] = shortBuffer[i] / 32768.0;
        }

        System.out.println(doubleInputBuffer);
//        for (int i = 0; i < buf.length; ++i) {
//            buf[i] = buf[i] / 32767.0;
//        }
//
        MFCC mfccConvert = new MFCC();
        double[][] mfccInput = mfccConvert.process(doubleInputBuffer);

        System.out.println(mfccInput);
    }


    private static int byteToInt(byte[] bytes) {
        int i = 0xff & bytes[0];
        i |= (bytes[1] << 8) & 0xff00;
        i |= (bytes[2] << 16) & 0xff0000;
        i |= (bytes[3] << 24) & 0xff000000;
        return i;
    }

    private static byte[] shortToBytes(short n) {
        byte[] targets = new byte[2];
        for (int i = 0; i < 2; i++) {
            int offset = (targets.length - 1 - i) * 8;
            targets[i] = (byte) ((n >>> offset) & 0xff);
        }
        return targets;
    }

    private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    public static String bytesToHexFun1(byte[] bytes) {
        // 一个byte为8位，可用两个十六进制位标识
        char[] buf = new char[bytes.length * 2];
        int a = 0;
        int index = 0;
        for(byte b : bytes) { // 使用除与取余进行转换
            if(b < 0) {
                a = 256 + b;
            } else {
                a = b;
            }

            buf[index++] = HEX_CHAR[a / 16];
            buf[index++] = HEX_CHAR[a % 16];
        }

        return new String(buf);
    }
}
